require([ 'jquery', 'common', 'validate','timepicker', 'pagination', 'bootstrap', 'dateZh','plupload','T_upload'], function($, common,validate,timepicker,T_upload) {
	
	var addProductBrandForm = $('#addTreeTypeForm');
	var updateProductBrandForm = $('#updateProductBrandForm');
	var addProductAttrForm = $('#addProductAttrForm');
	 
	$(function() { 
		showProductTypeByTree(1);  
		if (!placeholderSupport()) { // 判断浏览器是否支持 placeholder
			$('[placeholder]').focus(function() {
				var input = $(this);
				if (input.val() == input.attr('placeholder')) {
					input.val('');
					input.removeClass('placeholder');
				}
			}).blur(function() {
				var input = $(this);
				if (input.val() == ''
						|| input.val() == input.attr('placeholder')) {
					input.addClass('placeholder');
					input.val(input.attr('placeholder'));
				}
			}).blur();
		};
		  
	});
	function placeholderSupport() {
		return 'placeholder' in document.createElement('input');
	}
	//placeholder兼容ie end
	
	$(document).on('click', '.tree-typename', function(){
		var level = $(this).data("level"); 
		var id = $(this).data("id"); 
		var typeName = $(this).data("typename"); 
		if(level == 3) {	 
			$("#addProductAttrForm").find("input[name='productTypeId']").val(id);
			$("#addProductAttrForm").find("input[name='productTypeName']").val(typeName); 
			showProductAttribute(id, typeName);
		}
	});
	
	/** 分类属性查询start **/
	function showProductAttribute(id, typeName) {
		if ($(".all").is(':checked')) {
			$(".all").removeAttr('checked');								
		}	
		if($('.alert-warning').length>0){
    		$('.alert-warning').remove();
    	}
		$.getJSON(ctx + '/productattribute/list', {	  
				productTypeId : id
			},
			function(data){  
				if($('.loading')){
					$('.loading').remove();
				}
				var result = data.result;
				if(result!=null && result=="noauthority") {
					common.alert1('你无此权限!');
					return;
				}
				if(data.result!=null && data.result=="againLogin") {
					common.alert1("登录过期，请重新登录");
						setTimeout("location.href = ctx + '/login.html'",1000);
       			} else{ 
                    var tempHtml="";   
                    var ser = 1;
                    var datalist = data.list;
                    for(var i=0;i<datalist.length;i++){   
                    	var dto = datalist[i]; 
                    	tempHtml +="<tr data-id='"+dto.id+"'>";
                    	tempHtml +="<td><div class='checkbox'><label><input type='checkbox' data-roleid="+dto.id+" name='itemCheck' value="+dto.id+" /></label></div></td>";
                    	tempHtml +="<td>"+ser+"</td>"; 
                    	tempHtml +="<td>"+typeName+"</td>"; 
                    	tempHtml +="<td>"+dto.attrKey+"</td>";
                    	tempHtml +="<td>"+dto.attrValue+"</td>";  
                    	ser = ser + 1;
                    	tempHtml +="</tr>";
                    	if($('.alert-warning').length>0){
                    		$('.alert-warning').remove();
                    	}
                    }   
                    if(datalist.length === 0&&$('.alert-warning').length<=0) { 
						$('.table-responsive').append('<div class="alert alert-warning no-result text-center" role="alert">没有找到记录 </div>');
	                } 
                    $('#dataBody').html(tempHtml); 
				} 
			}).fail(function (err) { 
				if($('.loading')){
					$('.loading').remove();
				}
				common.alert('服务器错误！请刷新页面重试或联系管理员',"确定"); 
            });  
	}
	/** 分类属性查询end **/
	
	//新增分类属性
	$("#btn_add_attr").click(function(e){
		var isValid = addProductAttrForm.valid();
		var url; 
		url = ctx + '/productattribute/save'; 
    	 $.post(url, $('#addProductAttrForm').serialize(),function (data) {
     		if(data.result!=null && data.result=="againLogin"){
         		$('.commonConfirm').modal('hide');
         		common.alert1("登录过期，请重新登录");
				setTimeout("location.href = ctx + '/login.html'",1000);
        	}else if(data.result=='success'){
        		$('.modal-add').modal('hide');
        		common.mySuccessModal2(data.message);
      	        $("#addProductAttrForm").find("input[name='attrKey']").val('');
      			$("#addProductAttrForm").find("input[name='attrValue']").val('');
      			showProductAttribute($("#addProductAttrForm").find("input[name='productTypeId']").val(),
    					$("#addProductAttrForm").find("input[name='productTypeName']").val());
          	}else if(data.result=='fail'){
          		$(".errorMsg").html(data.message);
          	}else{
          		$(".errorMsg").html("信息提交错误");
          	}
          },"json");  
	});
	
	/**批量删除分类属性s*/
	$('#deleteMany').click(function(e) {
		var ids = "";
		var count = 0;
		var checks = document.getElementsByName("itemCheck"); 
		for(var i=0;i<checks.length;i++){
			if(checks[i].checked){
				count++;
				ids += checks[i].value + ",";
			}
		}
		if(count<1){
			common.alert1("请至少选择一个");
		}else{
			$('.commonConfirm').modal('show');
			common.commonConfirm("删除", "确定删除", "这"+count+"个吗",
				function() {
	            	 $.post(ctx+"/productattribute/deletebyids", {ids:ids},
	            		function (data) {
		            		 var result = data.result;
		     				 if(result!=null && result=="noauthority") {
		     					 common.alert1('你无此权限!');
		     					 return;
		     				 }
	    		    		 if(data.result!=null && data.result=="againLogin") {
	    		    			 $('.commonConfirm').modal('hide');
	    		    			 common.alert1("登录过期，请重新登录");
	    						 setTimeout("location.href = ctx + '/login.html'",1000);
	    		             }else if(data.result=='success'){ 
	    		         		 $(".commonConfirm").modal('hide');
	    		     	         common.mySuccessModal2(data.message);
	    		     	        showProductAttribute($("#addProductAttrForm").find("input[name='productTypeId']").val(),
	    	        					$("#addProductAttrForm").find("input[name='productTypeName']").val());
	    		         	}else{
	    		         		$(".updateMsg").html(data.message);
	    		         	}
	    		 },"json"); 
			});
		}
	});
	/**批量删除分类属性e*/

	/** 列表查询start **/
	function showProductTypeByTree() {
		$('#browser').html("");
		if ($(".all").is(':checked')) {
			$(".all").removeAttr('checked');								
		}	
		if($('.alert-warning').length>0){
    		$('.alert-warning').remove();
    	} 
		
		$.getJSON(ctx + '/producttype/tree', {	 
				status : $("select[name='status']").val()
			},
			function(data){  
				if($('.loading')){
					$('.loading').remove();
				}
				var result = data.result;
				if(result!=null && result=="noauthority") {
					common.alert1('你无此权限!');
					return;
				}
				if(data.result!=null && data.result=="againLogin") {
					common.alert1("登录过期，请重新登录");
						setTimeout("location.href = ctx + '/login.html'",1000);
       			} else if(data.result.length == 0) { 
					$('.table-responsive').append('<div class="alert alert-warning no-result text-center" role="alert">没有找到记录 </div>');
                } else{
                	tempHtml = "";
       				var treeData = data.result; 
       				parseTreeData(treeData);
                    $('#browser').html(tempHtml);
                    //树形样式设置s
                    $("#browser").treeview({
        				toggle: function() {
        					console.log("%s was toggled.", $(this).find(">span").text());
        				}
        			}); 
        			$("#add").click(function() {
        				var branches = $("<li><span class='folder'>New Sublist</span><ul>" +
        					"<li><span class='file'>Item1</span></li>" +
        					"<li><span class='file'>Item2</span></li></ul></li>").appendTo("#browser");
        				$("#browser").treeview({
        					add: branches
        				});
        			});    
        			//树形样式设置e
        			
                	if($('.alert-warning').length>0){
                		$('.alert-warning').remove();
                	}  
                    if(treeData.length === 0&&$('.alert-warning').length<=0) { 
						$('.table-responsive').append('<div class="alert alert-warning no-result text-center" role="alert">没有找到记录 </div>');
	                }  
				} 
			}).fail(function (err) { 
				if($('.loading')){
					$('.loading').remove();
				}
				common.alert('服务器错误！请刷新页面重试或联系管理员',"确定"); 
            });  
	}
	
	var tempHtml = "";
	function parseTreeData(treeData) { 
		for(var i=0;i<treeData.length;i++){   
			var data = treeData[i];  
			console.log("递归类型名称：" + data.typeName);
			tempHtml +="<li class='opened' data-id=" + data.id + " data-typeName= " + data.typeName + ">";
			tempHtml +="<span class='tree-typename' data-typename=" + data.typeName + " data-id=" + data.id + " data-id=" + data.id + "  " +
					"data-level="+ data.level +">"+data.typeName+"</span> " +
							"<img onClick='addTreeProductType(" + data.id + "," + data.level + " )' class='treeBtn' src='img/tree-add.JPG'>  " +
					"<img class='treeBtn' onClick='updateTreeProductType(" + data.id + ",\"" + data.typeName + "\" )' src='img/tree-mod.JPG'> " +
					"<img class='treeBtn delete-btn' data-id=" + data.id + " src='img/tree-del.JPG'> ";
			tempHtml +="<ul>";
			if(data.subset !=null && data.subset.length > 0) {
				var subset = data.subset
				parseTreeData(subset);
			}
			tempHtml +="</li>"; 
			tempHtml +="</ul>"; 
		}
	}
	/** 列表查询end **/
	
	
	/**删除start */
	$(document).on('click', '.delete-btn', function(){
		var id = $(this).data("id"); 
		$('.commonConfirm').modal('show');				
		common.commonConfirm("删除", "确定删除", "",
			function() {
            	 $.post(ctx+"/producttype/deletebyid", {
    				 id:id
    			 },function (data) {
    				 var result = data.result;
					 if(result!=null && result=="noauthority") {
						 common.alert1('你无此权限!');
						 return;
					 }
    	    		 if(data.result!=null && data.result=="againLogin") {
    	    			 $('.commonConfirm').modal('hide');
    	    			 common.alert1("登录过期，请重新登录");
    					 setTimeout("location.href = ctx + '/login.html'",1000);
    	             }else if(data.result=='success'){ 
    	            	$('.commonConfirm').modal('hide');
    	     	        common.mySuccessModal2(data.message);
    	     	       showProductTypeByTree();
    	         	}else{
    	         		common.alert1(data.message);
    	         	}
    	         },"json"); 
			}
		);
	});
	/** 删除end **/
	
	
	//添加顶级
	$("#btn_add").click(function(e){
		var isValid = addProductBrandForm.valid();
		var url; 
		url = ctx + '/producttype/save'; 
    	 $.post(url, $('#addProductBrandForm').serialize(),function (data) {
     		if(data.result!=null && data.result=="againLogin"){
         		$('.commonConfirm').modal('hide');
         		common.alert1("登录过期，请重新登录");
				setTimeout("location.href = ctx + '/login.html'",1000);
        	}else if(data.result=='success'){
        		$('.modal-add').modal('hide');
        		common.mySuccessModal2(data.message);
        		showProductTypeByTree(); 
      	        $("#addProductBrandForm").find("input[name='brandName']").val('');
      			$("#addProductBrandForm").find("input[name='alias']").val(''); 
      			
          	}else if(data.result=='fail'){
          		$(".errorMsg").html(data.message);
          	}else{
          		$(".errorMsg").html("信息提交错误");
          	}
          },"json");  
	});
	
	//添加树子级
	$("#btn_add_tree").click(function(e){
		var isValid = addProductBrandForm.valid();
		var url; 
		url = ctx + '/producttype/save'; 
    	 $.post(url, $('#addTreeTypeForm').serialize(),function (data) {
     		if(data.result!=null && data.result=="againLogin"){
         		$('.commonConfirm').modal('hide');
         		common.alert1("登录过期，请重新登录");
				setTimeout("location.href = ctx + '/login.html'",1000);
        	}else if(data.result=='success'){
        		$('.modal-add-tree').modal('hide');
        		common.mySuccessModal2(data.message);
        		showProductTypeByTree(); 
      	        $("#addTreeTypeForm").find("input[name='typeName']").val('');
      			$(".errorMsg").html('');  
          	}else if(data.result=='fail'){
          		$(".errorMsg").html(data.message);
          	}else{
          		$(".errorMsg").html("信息提交错误");
          	}
          },"json");  
	});

	/** 修改start **/
	$("#btn_update").click(function() { 
     	 $.post(ctx+"/producttype/update", $('#updateProductTypeForm').serialize(),function (data) {
     		var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
     		 if(result!=null && result=="againLogin") {
    			 $('.commonConfirm').modal('hide');
    			 common.alert1("登录过期，请重新登录");;
				 setTimeout("location.href = ctx + '/login.html'",1000);
             }else if(result=='success'){ 
          		 $(".modal-edit").modal('hide');
      	         common.mySuccessModal2('修改成功!');
      	         $("#updateProductTypeForm").find("input[name='id']").val("");
      	         $('#updateProductTypeForm').find("input[name='typeName']").val("");
      	       showProductTypeByTree();
          	}else{
          		$(".updateMsg").html(data.message);
          	}
          },"json"); 
	});
	/** 修改end **/
});

function addTreeProductType(parentId, level){
	$('.modal-add-tree').modal('show');		 
	$("#addTreeTypeForm").find("input[name='parentId']").val(parentId);
	$("#addTreeTypeForm").find("input[name='level']").val(level);
}

function updateTreeProductType(id, typeName){
	$('.modal-edit').modal('show');		 
	$("#updateProductTypeForm").find("input[name='id']").val(id);
	$("#updateProductTypeForm").find("input[name='typeName']").val(typeName);
} 
